import router from 'umi/router';
import { message } from 'antd';
import {
  queryNotices,
  queryInitNotices,
  updateState,
  getUrl,
  getNoticeCount,
  clearAllNotice,
  getNoticeNum,
} from '@/services/api';
import notifiImg from '../assets/notice.png';
import messageImg from '../assets/message.png';

export default {
  namespace: 'global',

  state: {
    collapsed: false,
    notices: [],
    loadedAllNotices: true,
    loadedLeftNotices: true,
    loadedRightNotices: true,
    sendType: 1, // 1:通知 2：消息
    totalCount: 0,
    noticeCurrentPage: 2,
    messageCurrentPage: 2,
    unreadCount: 0,
    pathMenu: '',
    socketTask: {},
  },

  effects: {
    *clearReduxData(
      {
        payload: { location, action },
      },
      { put, select }
    ) {
      const pathArr = location.pathname.split('/');
      const pathMenu = yield select(state => state.global.pathMenu);
      if (
        action === 'PUSH' &&
        (pathMenu === 'searches' || pathMenu === 'searchcs' || pathMenu === 'searchns')
      ) {
        return;
      }
      if (action === 'REPLACE' && location.pathname === '/user/login') {
        // 登录超时
        return;
      }
      if (
        action === 'PUSH' &&
        (location.pathname === '/searchmanage/policysearch/detail' ||
          location.pathname === '/searchmanage/policysearch/foundDetail')
      ) {
        // 登录超时
        return;
      }
      if (pathArr.length >= 3 && pathArr[2] !== pathMenu) {
        yield put({
          type: 'CLEAR_STORE',
        });
        yield put({
          type: 'setPathMenu',
          payload: { pathMenu: pathArr[2] },
        });
      }
    },

    // 查询消息列表
    *fetchInitNotices({ payload }, { call, put }) {
      const response = yield call(queryInitNotices, payload);
      if (response.success) {
        const resData = response.data.pageRecords;
        yield put({
          type: 'setLoadedStatus',
          payload: {
            data: response.data,
          },
        });

        // 处理通知显示格式
        yield put({
          type: 'saveNotices',
          payload: resData ? resData.filter(item => item) : [],
        });
      }
    },

    *setSendType({ payload }, { put, select }) {
      const { sendType } = payload;
      const loadedLeftNotices = yield select(state => state.global.loadedLeftNotices);
      const loadedRightNotices = yield select(state => state.global.loadedRightNotices);
      const loadedAllNotices = sendType === 1 ? loadedLeftNotices : loadedRightNotices;
      yield put({
        type: 'updateModelData',
        payload: {
          sendType,
          loadedAllNotices,
        },
      });
    },

    *fetchNoticeNum({ payload }, { call, put }) {
      const response = yield call(getNoticeNum, payload);
      if (response.success) {
        if (response.data.length > 0) {
          const noticeCount = +response.data[0];
          const messageCount = +response.data[1];
          const notifyTotalCount = Number(response.data[0]) + Number(response.data[1]);
          yield put({
            type: 'user/updateCurrentUserData',
            payload: { noticeCount, messageCount, notifyTotalCount },
          });
        }
      } else {
        message.warning(response.message || '服务端错误！');
      }
    },

    *fetchMoreNotices({ payload }, { call, put }) {
      const response = yield call(queryNotices, payload);
      const { currentPage } = payload;
      let data = [];
      if (response.success) {
        data = response.data.pageRecords;
        yield put({
          type: 'setCurrentPage',
          payload: { currentPage },
        });
        yield put({
          type: 'setLoadedStatus',
          payload: { data: response.data },
        });
        yield put({
          type: 'pushNotices',
          payload: data.filter(item => item),
        });
      }
    },
    *clearNotices({ payload, callback }, { call, put, select }) {
      const response = yield call(clearAllNotice, payload);
      const sendType = yield select(state => state.global.sendType);
      const type = sendType === 1 ? 'notification' : 'message';
      const notices = yield select(state =>
        state.global.notices.filter(item => item.type !== type)
      );
      if (response.success) {
        yield put({
          type: 'fetchNoticeNum',
          payload: {},
        });
        yield put({
          type: 'updateModelData',
          payload: {
            notices,
          },
        });

        if (callback) {
          callback();
        }
      }
    },
    *changeNoticeReadState({ payload }, { call, put, select }) {
      const data = yield call(updateState, payload); // 修改消息已读状态
      if (data.success) {
        yield put({
          type: 'fetchNoticeNum',
          payload: {},
        });
        const notices = yield select(state =>
          state.global.notices.map(item => {
            const notice = { ...item };
            if (notice.id === payload.sysMsgId) {
              notice.read = true;
            }
            return notice;
          })
        );
        yield put({
          type: 'updateModelData',
          payload: { notices },
        });
      } else {
        message.warning(data.message || '服务端错误！');
      }
    },
    *fetchMsgUrl({ payload, callback }, { call }) {
      const response = yield call(getUrl, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      } else {
        message.warning(response.message || '服务端错误！');
      }
    },

    *fetchNoticeCount({ payload }, { call, put }) {
      const response = yield call(getNoticeCount, payload);
      if (response.success) {
        yield put({
          type: 'user/changeNotifyCount',
          payload: {
            totalCount: response.data,
            unreadCount: response.data,
          },
        });
      }
    },
  },

  reducers: {
    changeLayoutCollapsed(state, { payload }) {
      return {
        collapsed: payload,
      };
    },
    returnNotices(state, { payload }) {
      return {
        ...state,
        notices: payload,
      };
    },
    saveNotices(state, { payload }) {
      let tempArr = [];
      if (payload && payload.length) {
        tempArr = payload.map(item => ({
          id: item.sysMsgId,
          datetime: item.creTime,
          type: Number(item.sendType) === 1 ? 'notification' : 'message',
          clickClose: Number(item.sendType) === 1,
          avatar: Number(item.sendType) === 1 ? notifiImg : messageImg,
          title: item.title,
          description: item.content,
          vno: item.vno,
        }));
      }
      return {
        ...state,
        notices: tempArr,
      };
    },
    saveClearedNotices(state, { payload }) {
      const tempType = payload.sendType === 1 ? 'notification' : 'message';
      return {
        ...state,
        notices: state.notices.filter(item => item.type !== tempType),
      };
    },
    pushNotices(state, { payload }) {
      const { notices } = state;
      let tempArr = [];
      if (payload && payload.length) {
        tempArr = payload.map(item => ({
          id: item.sysMsgId,
          datetime: item.creTime,
          type: Number(item.sendType) === 1 ? 'notification' : 'message',
          clickClose: Number(item.sendType) === 1,
          avatar: Number(item.sendType) === 1 ? notifiImg : messageImg,
          title: item.title,
          description: item.content,
          vno: item.vno,
        }));
      }
      return {
        ...state,
        notices: notices.concat(tempArr),
      };
    },

    setCurrentPage(state, { payload }) {
      const tempPage = payload.currentPage;
      const { sendType } = state;
      let noticeCurrentPage;
      let messageCurrentPage;
      if (+sendType === 1) {
        noticeCurrentPage = tempPage + 1;
      } else if (+sendType === 2) {
        messageCurrentPage = tempPage + 1;
      } else {
        noticeCurrentPage = 2;
        messageCurrentPage = 2;
      }
      return {
        ...state,
        // ...payload,
        noticeCurrentPage,
        messageCurrentPage,
      };
    },

    setLoadedStatus(state, { payload }) {
      const {
        data: { pageRecords },
      } = payload;
      let loadedLeftNotices;
      let loadedRightNotices;
      if (pageRecords) {
        loadedLeftNotices = pageRecords.filter(item => item.sendType === 1).length < 5;
        loadedRightNotices = pageRecords.filter(item => item.sendType === 2).length < 5;
      }
      return {
        ...state,
        loadedLeftNotices,
        loadedRightNotices,
        loadedAllNotices: state.sendType === 1 ? loadedLeftNotices : loadedRightNotices,
      };
    },
    setPathMenu(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },

  subscriptions: {
    setup({ history, dispatch }) {
      return history.listen((location, action) => {
        const firstLoginFlag = window.sessionStorage.getItem('firstLoginFlag') || '2';
        if (
          firstLoginFlag === '1' &&
          location.pathname !== '/user/login' &&
          location.pathname !== '/more/setting/security'
        ) {
          router.push('/more/setting/security');
        }

        if (
          (location.pathname !== '/' || location.pathname !== '/user/login') &&
          (!location.query || !(location.query && location.query.isNoticeClick)) &&
          action !== 'POP'
        ) {
          dispatch({
            type: 'clearReduxData',
            payload: { location, action },
          });
        }
      });
    },
  },
};
